<?php

class Merchant extends Users
{

    public $biz_url;
    public $merchant_cat;

    /**
     * @param string $className
     * @return Merchant
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('email', 'validate_email'),
            array('email,business_name,office_phone', 'required'),
            array('email', 'email'),
            array('merchant_cat', 'validate_required'),
            array('biz_url', 'valie_biz_url'),
            array('office_phone,mobile_phone', 'check_validate_phone'),
            array('status,address,address2,business_name,business_slogan,facebook,twitter,gplus,instagram,website,business_logo,business_description,postal_code,firstname,lastname,birthday,city,country,home_phone,mobile_phone,office_phone,fax,photo,gender,occupation,note, latitude, longitude', 'safe'),
            array('new_pass', 'length', 'min' => 6),
            array('repassword', 'length', 'min' => 6, 'tooShort' => Yii::t('main', 'Password repeated is too short. (minimum 6 characters)')),
            array('repassword', 'compare', 'compareAttribute' => 'new_pass', 'message' => Yii::t('main', 'Password repeated is incorrect')),
        );
    }

    public function valie_biz_url($attribute, $params)
    {
        if (isset($_POST['Business']['biz_url']))
        {
            if ($_POST['Business']['biz_url'] == '')
            {
                $this->addError($attribute, Yii::t('main', 'Merchant profile page Url cannot be blank.'));
                return;
            }
        }
    }

    public function validate_required($attribute, $params)
    {
        if (Yii::app()->user->isAdmin())
        {

            if (isset($_POST['merchant_cat']))
            {
                //merchant cat is an array
                if (!is_array($_POST['merchant_cat']) || count($_POST['merchant_cat']) <= 0)
                {
                    $this->addError($attribute, Yii::t('main', 'Merchant Category cannot be blank.'));
                    return;
                }
            }
            else
            {
                $this->addError($attribute, Yii::t('main', 'Merchant Category cannot be blank.'));
                return;
            }
        }
    }

    public function check_validate_phone($attribute, $params)
    {
        if ($this->$attribute != '')
        {
            $a = trim($this->$attribute);
            $a = str_replace(' ', '', $a);
            if (!in_array($a[0], array('6', '9', '8')))
            {
                $this->addError($attribute, Yii::t('main', 'Please provide a valid phone number'));
            }
            return;
        }
    }

    //validate
    public function validate_email($attribute, $param)
    {

        if ($this->isNewRecord)
        {

            $exits_merchant = Users::model()->find('email=:email AND type=:type', array(
                ':email' => $this->email,
                ':type'  => Users::TYPE_BUSINESS
            ));
            if ($exits_merchant)
            {
                $this->addError($attribute, Yii::t('main', '"{email}" has taken', array('{email}' => $this->email)));
            }
        }
        else
        {// edit
            $exits_merchant = Users::model()->find('email=:email AND type=:type AND id!=:id', array(
                ':email' => $this->email,
                ':type'  => Users::TYPE_BUSINESS,
                ':id'    => $this->id,
            ));
            if ($exits_merchant)
            {
                $this->addError($attribute, Yii::t('main', '"{email}" has taken', array('{email}' => $this->email)));
            }
        }
    }

    public static function getRecordByUkey($ukey)
    {
        return Merchant::model()->find('ukey=:ukey', array(':ukey' => $ukey));
    }

    public static function getRecordById($id)
    {
        return Merchant::model()->findByPk($id);
    }

    public function afterSave()
    {
        if (parent::afterSave())
        {
            // Xóa ảnh Gallery
            if (isset($_POST['deleteGallery']))
            {
                foreach ($_POST['deleteGallery'] as $galleryId)
                {
                    $gallery = BusinessGallery::model()->findByPk($galleryId);

                    if ($gallery != null && $gallery->business_id = $this->id)
                    {
                        @unlink($gallery->image);
                        BusinessGallery::model()->deleteByPk($galleryId);
                    }
                }
            }


            if (@$_FILES[$name])
            {
                $file     = $_FILES[$name];
                $tmp_file = "files/user/" . md5(time() . $file['name']) . "_" . $file['name'];
                if (move_uploaded_file($file['tmp_name'], $tmp_file))
                {
                    $thumb = Yii::app()->phpThumb->create($tmp_file);
                    $thumb->adaptiveResize(130, 130);
                    $thumb->save($tmp_file);
                    return $tmp_file;
                }
            }
        }
    }

    //Return 1 mảng ID hoặc Ukey của các branh thuộc root merchant
    public static function getAllBranchByBusiness($id_bussiness, $ukey = FALSE)
    {
        if ($ukey === TRUE)
        {
            $user = Users::model()->find('ukey=:u', array(':u' => $id_bussiness));
            if ($user != NULL)
            {
                $id_bussiness = $user->id;
            }
        }

        $branchs = Users::model()->findAll("type=:t AND author_id=:a", array(
            ':t' => self::TYPE_BUSINESS,
            ':a' => $id_bussiness
        ));
        $ret     = array();
        $ret[]   = $id_bussiness;

        foreach ($branchs as $biz)
        {
            if ($ukey == TRUE)
            {
                $ret[] = $biz->ukey;
            }
            else
            {
                $ret[] = $biz->id;
            }
        }
        return $ret;
    }

    //Return 1 mảng Id/Ukey+Tên Branch
    public static function getListBranch($root_id, $ukey = FALSE)
    {
        $crite            = new CDbCriteria();
        $crite->select    = 'id, type, ukey, business_name';
        $crite->order     = 'business_name ASC';
        $crite->condition = 'type=:t AND author_id=:au';
        $crite->params    = array(':t' => self::TYPE_BUSINESS, ':au' => $root_id);

        $bizs    = self::model()->findAll($crite);
        $ret     = array();
        $ret[''] = Yii::t('main', 'This Merchant');
        //update for staff does not belong to any merchant

        foreach ($bizs as $biz)
        {
            if ($ukey == TRUE)
            {
                $ret[$biz->ukey] = $biz->business_name;
            }
            else
            {
                $ret[$biz->id] = $biz->business_name;
            }
        }

        return $ret;
    }

    /**
     * 
     * @return boolean <b>TRUE</b> if this is a branch 
     */
    public function getIsBranch()
    {
        return ($this->author_id != Users::SUPER_ADMIN) ? TRUE : FALSE;
    }

    public static function getAllStaffIdOfBranch($biz_id)
    {
        $branchs    = Users::model()->findAll("author_id=:bizid AND type=:type", array(
            ":bizid" => $biz_id,
            ":type"  => Users::TYPE_BUSINESS
        ));
        $branch_ids = array();
        foreach ($branchs as $branch)
        {
            $branch_ids[] = $branch->id;
        }

        $cri            = new CDbCriteria();
        $cri->addInCondition("author_id", $branch_ids);
        $cri->condition = "type=:type";
        $cri->params    = array(":type" => Users::TYPE_STAFF);

        $result = array();
        $staffs = Users::model()->findAll($cri);
        foreach ($staffs as $staff)
        {
            $result[] = $staff->id;
        }

        return $result;
    }

}
